package com.cqie.tes.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cqie.tes.comm.GlobalConstant;
import com.cqie.tes.comm.R;
import com.cqie.tes.comm.qo.BaseQo;
import com.cqie.tes.comm.service.IBaseService;
import com.cqie.tes.comm.service.impl.BaseServiceImpl;
import com.cqie.tes.config.MyUserDetile;
import com.cqie.tes.domain.*;
import com.cqie.tes.domain.vo.tes.evalute.result.RdVo;
import com.cqie.tes.domain.vo.tes.evalute.result.ResultTypeVo;
import com.cqie.tes.domain.vo.tes.evalute.result.ResultVo;
import com.cqie.tes.mapper.*;
import com.cqie.tes.service.ResultService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fall in love
 * @since 2021-10-15
 */
@Service
public class ResultServiceImpl extends BaseServiceImpl<ResultMapper, Result> implements ResultService {

    @Autowired
    ResultMapper resultMapper;
    @Autowired
    EmployeeMapper employeeMapper;
    @Autowired
    DeptMapper deptMapper;
    @Autowired
    EvalutetypeMapper evalutetypeMapper;
    @Autowired
    CourseclazzteacherMapper courseclazzteacherMapper;

    @Override
    public R getList(BaseQo query) {

        // 判断权限 先不写
        // MyUserDetile principal = (MyUserDetile) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        // 基础数据
        List<RdVo> entitys = resultMapper.selectResult();
        List<Long> teacherIds = entitys.stream().map(RdVo::getTeacherId).collect(Collectors.toList());

        // teacher 列表

        // 人员列表
        List<Employee> employeeList = employeeMapper.selectList(new QueryWrapper<Employee>()
                .lambda()
                .in(Employee::getId, teacherIds)
        );
        List<Integer> deptIds = employeeList.stream().map(Employee::getDeptId).collect(Collectors.toList());
        // 部门列表
        List<Dept> deptList = deptMapper.selectList(new QueryWrapper<Dept>()
                .lambda()
                .in(Dept::getId, deptIds)
        );
        // 类型列表
        List<Evalutetype> evalutetypeList = evalutetypeMapper.selectList(new QueryWrapper<Evalutetype>()
                .lambda()
                .eq(Evalutetype::getMark, 1)
        );
        // 课表
        List<Courseclazzteacher> courseclazzteacherList = courseclazzteacherMapper.selectList(new QueryWrapper<Courseclazzteacher>()
                .lambda()
                .eq(Courseclazzteacher::getMark, 1)
        );

        List<ResultVo> vos  = new ArrayList<>();


        // 构建数据

        entitys.forEach(entity->{
            System.out.println(entity);
            // 姓名
            Employee employee = employeeList.stream().filter(x -> x.getId().equals(entity.getTeacherId())).findFirst().orElse(new Employee());
            // 部门
            Dept dept = deptList.stream().filter(x -> x.getId().intValue()== employee.getDeptId()).findFirst().orElse(new Dept());
            // 类型
            Evalutetype evalutetype = evalutetypeList.stream().filter(x -> entity.getTypeId().equals(x.getId())).findFirst().orElse(new Evalutetype());

            ResultVo vo  = getResultVo(vos,entity.getTaskId(),entity.getTeacherId());
//            ResultVo vo  = new ResultVo();

            vo.setTaskId(entity.getTaskId());
            vo.setName(employee.getName());
            vo.setDeptName(dept.getName());
            vo.setDeptId(dept.getId());
            vo.setEmpId(entity.getTeacherId());

            // 应评人数
            Long shouldd = courseclazzteacherList.stream().filter(x->x.getEmpId() == employee.getId()).count();
            Integer should = shouldd.intValue();

            String score = String.format("%.2f", vo.getScore() == 0?entity.getAvg():(entity.getAvg()+vo.getScore())/2);
            vo.setScore(new Double(score));

            double avg = new Double(String.format("%.2f",entity.getAvg()));

            if (entity.getTypeId().equals(GlobalConstant.STUDENT_TYPE_ID)){
                // 学生评价
                ResultTypeVo student = new ResultTypeVo();
                student.setScore(avg);
                student.setReality(entity.getCount());
                student.setWeight(evalutetype.getWeight());
                student.setShould(should);
                vo.setStudent(student);
            }else if(entity.getTypeId().equals(GlobalConstant.TEACHER_ZERO_SELF_TYPE_ID)){
                ResultTypeVo teacherSelf = new ResultTypeVo();
                teacherSelf.setScore(avg);
                teacherSelf.setReality(entity.getCount());
                teacherSelf.setWeight(evalutetype.getWeight());
                teacherSelf.setShould(should);
                vo.setTeacherSelf(teacherSelf);
            }else if(entity.getTypeId().equals(GlobalConstant.TEACHER_ZERO_MUTUAL_TYPE_ID)){
                ResultTypeVo teacherEach = new ResultTypeVo();
                teacherEach.setScore(avg);
                teacherEach.setReality(entity.getCount());
                teacherEach.setWeight(evalutetype.getWeight());
                teacherEach.setShould(should);
                vo.setTeacherEach(teacherEach);
            }else if(entity.getTypeId().equals(GlobalConstant.TEACHER_ONE_TYPE_ID)){
                ResultTypeVo staff = new ResultTypeVo();
                staff.setScore(avg);
                staff.setReality(entity.getCount());
                staff.setWeight(evalutetype.getWeight());
                staff.setShould(should);
                vo.setStaff(staff);
            }else if(entity.getTypeId().equals(GlobalConstant.TEACHER_TWO_TYPE_ID)){
                ResultTypeVo department = new ResultTypeVo();
                department.setScore(avg);
                department.setReality(entity.getCount());
                department.setWeight(evalutetype.getWeight());
                department.setShould(should);
                vo.setDepartment(department);
            }

            vos.add(vo);
        });

        // 计算总分



        return R.ok().data("total",vos.size()).data("rows",vos);
    }

    public ResultVo getResultVo(List<ResultVo> vos,Long taskId,Long empId){
        ResultVo rvo = new ResultVo();

        int i = 0;
        for (ResultVo vo : vos) {
            if (vo.getEmpId()== empId && vo.getTaskId()== taskId){
                try {
//                    ResultVo clone = vo.clone();
                    ResultVo clone = vo;
                    vos.remove(i);
                    return clone;
                }catch (Exception e){
                    e.printStackTrace();
                    return rvo;
                }
            }
            i++;
        }
        return rvo;
    }
}
